﻿using DreamCMS.BLL;
using DreamCMS.BLL.Common;
using DreamCMS.Entity;
using DreamCMS.Entity.Common;
using DreamCMS.WebCore.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace DreamCMS.Web.Admin.ArtMgr
{
    public partial class AddArt : AdminPageBase
    {
        private string EditType = RequestHelper.GetQueryString("edittype", true);
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                InitFormInfo();
                if (EditType == "edit") //非回传且是编辑的情况下：肯定是用户正准备编辑或者添加/编辑后的跳转Redirect。
                {
                    //此时需要绑定数据
                    BindDataToForm();
                    if (Request.QueryString["msg"] == "successedit") //有信息说明是编辑后的Redirect
                    {
                        ClientScript.RegisterStartupScript(GetType(), "successAdd", "<script>alert('编辑成功');</script>");
                    }
                    if (Request.QueryString["msg"] == "successadd") //有信息说明是添加后的Redirect
                    {
                        ClientScript.RegisterStartupScript(GetType(), "successAdd", "<script>alert('添加成功');</script>");
                    }
                }
            }
        }

        /// <summary>
        /// 添加或保存文章
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void save_Click(object sender, EventArgs e)
        {
            PostInfo p = null;
            if (this.EditType == "edit")
            {
                long id = RequestHelper.QueryInt("id", 0);
                p = PostManager.GetPost(id);
            }
            else
            {
                p = new PostInfo();
                p.CreateDate = DateTime.Now;
                p.UserId = LoginHelper.CurrentUserId;
            }
            p.Title = title.Value;
            p.CategoryId = StringHelper.StrToInt64(catListControl.SelectedValue, 0);
            p.Slug = slug.Value;
            p.Status = isOpen.Checked == true ? PostStatus.Published : PostStatus.Draft;
            p.Recommend = isRecommended.Checked == true ? PostRecommend.Rec : PostRecommend.NotRec;
            p.TopStatus = isTop.Checked == true ? PostTopStatus.Top : PostTopStatus.NoTop;
            p.HideStatus = isHide.Checked == true ? PostHideStatus.Hide : PostHideStatus.NoHide;
            p.Content = postContent.Text;
            p.Summary = summary.Value;
            p.UpdateDate = DateTime.Now;
            p.Tag = GetTagIdList(tag.Value.Trim());
            if (upImage.HasFile)
            {
                System.IO.Stream fileStream = upImage.PostedFile.InputStream;
                string randName= VerifyCodeHelper.GetCode(16)+IOHelper.GetExtName(upImage.FileName);
                ImageHelper.CutForCustom(fileStream, Server.MapPath("~/uploads/thumb/" +randName), 300, 180, 95);
                p.imageUrl = randName;
            }

            if (this.EditType == "edit")
            {
                if (PostManager.UpdatePost(p) > 0)
                {
                    Response.Redirect("AddArt.aspx?edittype=edit&id=" + p.PostId + "&msg=successedit");
                }

            }
            else
            {
                PostManager.InsertPost(p);
                Response.Redirect("AddArt.aspx?edittype=edit&id=" + p.PostId + "&msg=successadd");
            }
        }

        private void InitFormInfo()
        {
            catListControl.Items.Clear();
            List<CategoryInfo> list = CategoryManager.GetCategoryList();
            if (list.Count == 0 || list == null)
            {
                catListControl.Items.Add(new ListItem("无分类", "0"));
                return;
            }
            foreach (CategoryInfo cat in list)
            {
                catListControl.Items.Add(new ListItem(cat.Name, cat.CatId.ToString()));
            }
        }

        private void BindDataToForm()
        {
            long postId = RequestHelper.QueryInt("id", 0);
            PostInfo p = PostManager.GetPost(postId);
            if (p == null)
            {
                return;
            }
            title.Value = StringHelper.HtmlDecode(p.Title);
            slug.Value = StringHelper.HtmlDecode(p.Slug);
            catListControl.SelectedValue = p.CategoryId.ToString();
            isOpen.Checked = (p.Status == 0) ? false : true;
            isRecommended.Checked = (p.Recommend == 0) ? false : true;
            isTop.Checked = (p.TopStatus == 0 ? false : true);
            isHide.Checked = (p.HideStatus == 0 ? false : true);
            postContent.Text = p.Content;
            summary.Value = p.Summary;

            //绑定标签,需改进
            string taginfo = p.Tag;
            taginfo = taginfo.Replace("{", "");
            string[] taglist = taginfo.Split('}');
            foreach (string tagId in taglist)
            {
                TagInfo onetaginfo = TagManager.GetTag(StringHelper.StrToInt64(tagId, 0));

                if (onetaginfo != null)
                {
                    tag.Value += onetaginfo.Name + ",";
                }
            }
            tag.Value = tag.Value.TrimEnd(',');

        }

        /// <summary>
        /// 由标签名称列表返回标签ID列表,带{},新标签自动添加
        /// </summary>
        /// <param name="tagNameList"></param>
        /// <returns>本篇文章的标签ID序列，用于保存到文章记录数据库</returns>
        protected string GetTagIdList(string tagNames)
        {
            if (string.IsNullOrEmpty(tagNames))
            {
                return string.Empty; //用户没有填写标签，则返回一个空。该文章数据库里面标签字段就插入空即可。
            }
            //若用户填写了标签表单，则：
            string tagIds = string.Empty;
            tagNames = tagNames.Replace("，", ","); //先把中文逗号替换为英文，解决用户输入错误的问题。

            string[] names = tagNames.Split(',');

            foreach (string n in names)
            {
                if (!string.IsNullOrEmpty(n))
                {
                    TagInfo t = TagManager.GetTag(n); //找到Term表中的这个标签

                    if (t == null) //如果Term表中没有用户输入的标签，那么就要在Terms表中新插入这个标签
                    {
                        t = new TagInfo();
                        t.Postcount = 0;
                        t.Createdate = DateTime.Now;
                        t.Description = n;
                        t.Displayorder = 1000;
                        t.Name = n;
                        //TODO:Slug需要过滤操作，以避免出现非字母的其他字符。过滤函数在此省略了。以后补充。
                        t.Slug = StringHelper.HtmlEncode(n);
                        t.Tagid = TagManager.InsertTag(t);
                    }
                    tagIds += "{" + t.Tagid + "}";  //序列化文章记录中要保存的标签ID序列。
                }
            }
            return tagIds; //返回本篇文章要保存的标签ID序列
        }
    }
}